package com.hmily.spring.samples.trace;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * <h1>追踪ID的拦截器处理类。</h1>
 *
 * @author hmilyylimh
 * ^_^
 * @version 0.0.1
 * ^_^
 * @date 2021-10-31
 */
public class TraceIntercepter extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(TraceFilter.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        attachTraceId(request);

        return super.preHandle(request, response, handler);
    }

    /**
     * <h2>绑定追踪ID。</h2><br/>
     *
     * <li>注意1：如果该系统不是第一个发起的的应用系统，那么我们的追踪ID需要从 request 里面解析获取。</li>
     * <li>注意2：目前我把该应用当作第一个系统，那么该应用就需要自己创建全局的唯一ID。</li>
     *
     * @param request
     */
    private void attachTraceId(HttpServletRequest request) {
        String traceId = UUID.randomUUID().toString().replace("-", "");
        String spanId = UUID.randomUUID().toString().replace("-", "");

        MDC.put(TraceConsts.TRACE_ID, traceId);
        MDC.put(TraceConsts.SPAN_ID, spanId);

        logger.info("traceId={}, spanId={}", traceId, spanId);
    }
}